/**
 * 币安API模块
 */
const axios = require('axios');
const logger = require('./logger');

// 获取K线数据
async function getKlines(symbol, interval, limit = null, startTime = null, endTime = null) {
    try {
        const params = {
            symbol,
            interval
        };
        
        // 只有当limit参数提供时才添加
        if (limit) {
            params.limit = limit;
        }
        
        // 添加时间范围参数（如果提供）
        if (startTime) {
            params.startTime = startTime;
        }
        
        if (endTime) {
            params.endTime = endTime;
        }
        
        logger.info(`请求币安K线数据: symbol=${symbol}, interval=${interval}, startTime=${startTime ? new Date(parseInt(startTime)).toLocaleString() : 'null'}, endTime=${endTime ? new Date(parseInt(endTime)).toLocaleString() : 'null'}`);
        
        const response = await axios.get('https://api.binance.com/api/v3/klines', {
            params,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
        });
        
        logger.info(`币安返回 ${response.data.length} 条K线数据`);
        
        // 返回原始数据数组，而不是转换后的对象
        return response.data;
    } catch (error) {
        logger.error('获取币安K线数据失败:', error.message);
        return null;
    }
}

// 获取当前价格
async function getCurrentPrice(symbol) {
    try {
        const response = await axios.get('https://api.binance.com/api/v3/ticker/price', {
            params: { symbol },
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
        });
        return parseFloat(response.data.price);
    } catch (error) {
        logger.error('获取币安当前价格失败:', error.message);
        return null;
    }
}

module.exports = {
    getKlines,
    getCurrentPrice
}; 